extends IArea2DComponent


class_name PickupBoxComponent


## 挂载的背包
@export var knapsack: IInventoryComponent = null

@export_category("Capture")
@export var capture_squared_distance: float = 0
@export_range(0.0, 1.0, 0.1) var capture_lerp: float = 0.5
@export_category("")


var follow_items: Array[PickableComponent] = []


func __check_exports() -> Dictionary:
    return IComponent.merge({
        "knapsack": IComponent.find_down_nearby.bind(self, func(x): return x is IInventoryComponent, knapsack),
    }, super.__check_exports())

func __init_hooks() -> Dictionary:
    return IComponent.merge({
        area_entered: __on_pickable_enter,
    }, super.__init_hooks())

func __prepare() -> void:
    super.__prepare()
    set_physics_process(false)

func pickup(pickable: PickableComponent) -> bool:
    return knapsack.pickup(pickable.item)

func __on_pickable_enter(body: Node2D) -> void:
    if body is PickableComponent and not body.is_captured:
        body.is_captured = true
        if capture_squared_distance > 0:
            follow_items.append(body)
            set_physics_process(true)
        else:
            pickup(body)
            GameService.destroy(body)

func __follow_this(item: PickableComponent) -> bool:
    if item.global_position.distance_squared_to(global_position) < capture_squared_distance:
        return true
    item.global_position = item.global_position.lerp(global_position, capture_lerp)
    return false

func _physics_process(delta: float) -> void:
    var rm_list: Array[PickableComponent] = []
    for item in follow_items:
        if __follow_this(item):
            rm_list.append(item)
    for item in rm_list:
        pickup(item)
        follow_items.erase(item)
        GameService.destroy(item)
    if follow_items.size() < 1:
        set_physics_process(false)
